package com.reading.common.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 公共类工具
 */
public class WebUtil {

    /**
     * 小端字节序->大端字节序
     *
     * @param bytes
     * @return
     */
    public static int byteLittleEndianToInt(byte[] bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, 4);
        IntBuffer intBuffer = byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
        return intBuffer.get();
    }

    /**
     * 小端字节序->大端字节序
     *
     * @param bytes
     * @return
     */
    public static short byteLittleEndianToShort(byte[] bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, 2);
        ShortBuffer shortBuffer = byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
        return shortBuffer.get();
    }

    /**
     * 大端字节序->小端字节序
     *
     * @param i
     * @return
     */
    public static byte[] shortToMinByteArray(short i) {
        byte[] result = new byte[2];
        //由高位到低位
        result[1] = (byte) ((i >> 8) & 0xFF);
        result[0] = (byte) (i & 0xFF);
        return result;
    }

    /**
     * short转换为byte[]
     * @param number
     * @return byte[]
     */
    public static byte[] shortToByte(short number) {
        int temp = number;
        byte[] b = new byte[2]; // 将最低位保存在最低位
        b[0] = (byte)(temp & 0xff);
        temp = temp >> 8; // 向右移8位
        b[1] = (byte)(temp & 0xff);
        return b;
    }

    public static String httpRequest(String requestUrl, Map<String, Object> heads, String requestMethod, String requestBody) {
        BufferedOutputStream out = null;
        try {
            URL url = new URL(requestUrl);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "close");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //设置读写超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-Type", "application/json");

            //若头信息存在，则增加头信息设置，覆盖掉通用配置
            if (heads != null) {
                Iterator<Map.Entry<String,Object>> iterator = heads.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String,Object> entry = iterator.next();
                    conn.setRequestProperty(entry.getKey(), (String) entry.getValue());
                }
            }

            conn.connect();

            if ("POST".equalsIgnoreCase(requestMethod) && !StringUtils.isEmpty(requestBody)) {
                // 获取URLConnection对象对应的输出流
                out = new BufferedOutputStream(conn.getOutputStream());
                // 发送请求参数
                out.write(requestBody.getBytes("UTF-8"));
                // flush输出流的缓冲
                out.flush();
            }

            // 获取所有响应头字段
            //Map<String, List<String>> responseHeaders = conn.getHeaderFields();
            return streamToString(conn.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    private static String streamToString(InputStream in) {
        ByteArrayOutputStream bin = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) != -1) {
                bin.write(buffer, 0, length);
            }
            return bin.toString(StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            IOUtils.closeQuietly(bin);
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     **/
    public static String httpsRequest(String requestUrl, Map<String, Object> heads, String requestMethod, String requestBody, TrustManager[] trustManager) {
        BufferedOutputStream out = null;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            //初始化
            sslContext.init(null, trustManager, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "close");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //设置读写超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-Type", "application/json");

            //若头信息存在，则增加头信息设置，覆盖掉通用配置
            if (heads != null) {
                Iterator<Map.Entry<String,Object>> iterator = heads.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String,Object> entry = iterator.next();
                    conn.setRequestProperty(entry.getKey(), (String) entry.getValue());
                }
            }

            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();

            //往服务器端写内容
            if ("POST".equalsIgnoreCase(requestMethod) && !StringUtil.isEmpty(requestBody)) {
                // 获取URLConnection对象对应的输出流
                out = new BufferedOutputStream(conn.getOutputStream());
                // 发送请求参数
                out.write(requestBody.getBytes("UTF-8"));
                // flush输出流的缓冲
                out.flush();
            }

            // 获取所有响应头字段
            //Map<String, List<String>> responseHeaders = conn.getHeaderFields();
            //读取服务器端返回的内容
            return streamToString(conn.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            IOUtils.closeQuietly(out);
        }
    }


    /**
     * 模拟请求
     *
     * @param url 资源地址
     * @param map 参数列表
     * @return
     * @throws Exception
     */
    public static String sendHttp(String url, Map<String, String> map) throws Exception {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

        //设置header信息
        //指定报文头【Content-type】、【SysUser-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("SysUser-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }


    /**
     * 模拟请求
     *
     * @param url      资源地址
     * @param map      参数列表
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String sendHttps(String url, Map<String, String> map) throws Exception {
        String body = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

        //设置header信息
        //指定报文头【Content-type】、【SysUser-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("SysUser-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }

}
